#!/usr/bin/python
# -*- coding: utf-8 -*-

import re


def Client(tgt, module, argv):
    import salt.client

    local = salt.client.LocalClient()
    if argv:
        result = local.cmd(tgt, module, [argv], tgt_type='list')
    else:
        result = local.cmd(tgt, module, tgt_type='list')
    return result


def Os(tgt):
    os_argvs = ['localhost', 'kernel', 'kernelrelease', 'cpu_model', 'num_cpus', 'productname', 'os', 'osrelease',
                'mem_total']

    os_module = 'grains.item'

    oss = {}
    for argv in os_argvs:
        result = Client(tgt, os_module, argv)
        oss[argv] = result

    os_info = {}

    for ip in tgt:
        try:
            os_list = {}

            for argv in os_argvs:
                data = oss[argv][ip][argv]
                os_list[argv] = data
            os_info[ip] = os_list
        except:
            pass
    return os_info


def Disk(tgt):
    argv = "fdisk -l | grep -E 'sda:|sdb:|sdc:|vda:|vdb:|vdc:' |awk -F ',' '{print $1}'"
    disk_module = 'cmd.run'

    result = Client(tgt, disk_module, argv)
    disk_dict = {}

    for i in result.keys():
        disk_infos = []

        if re.search("Disk", result[i]):
            disk_infos = result[i].split("\n")
        else:
            argv = None
            disk_module = 'disk.usage'
            ip_tgt = [i]
            result_w = Client(ip_tgt, disk_module, argv)
            for j in result_w.keys():

                for k in result_w[j].keys():
                    disk_size = result_w[j][k]["1K-blocks"]

                    if disk_size:
                        disk = k.strip("\\") + str(disk_size / 1024 / 1024) + " GB"
                        disk_infos.append(disk)
                    else:
                        pass

        disk_info = sorted(disk_infos)
        disk_dict[i] = {"disk_info": disk_info}
    return disk_dict


def Mem(tgt):
    argv = None
    module = 'status.meminfo'
    result = Client(tgt, module, argv)

    mem_info = {}

    for ip in tgt:
        try:
            SwapTotal = int(result[ip]['SwapTotal']['value']) / 1024
        except:
            SwapTotal = 0

        mem_info[ip] = {"SwapTotal": SwapTotal}

    return mem_info


def main(tgt):
    os_info = Os(tgt)
    disk_info = Disk(tgt)
    mem_info = Mem(tgt)
    data = {}
    for ip in tgt:
       try:
           sys_info = dict(os_info[ip].items() + disk_info[ip].items() + mem_info[ip].items())
           data[ip] = sys_info
       except:
           pass
    return data


if __name__ == '__main__':
    tgt = [u'192.168.1.197','192.168.1.199','192.168.1.198','192.168.1.196']
    result = main(tgt)
    print result
